<template>
  <div class="component-container">
    <h1 class="title">设备管理</h1>
    <div class="search-bar">
      <div class="left">
        <el-select v-model="searchData.productKey" placeholder="请选择" style="width: 160px; margin-right: 80px;" clearable @change="searchAllData">
          <el-option value label="全部产品"></el-option>
          <el-option
            :value="product.productkey"
            :label="product.name"
            v-for="product in productList"
            :key="product.productkey"
          ></el-option>
        </el-select>
        <div class="preview">
          <div class="preview-item">
            <header>
              <span class="status-green"></span>
              <span>当前在线</span>
              <el-popover
                placement="top"
                trigger="hover"
                content="当前在线的设备总数">
                <i class="el-icon-question" slot="reference"></i>
              </el-popover>
            </header>
            <div class="number" v-loading="loadingOnlineSwitchAmount">{{statisticsData.onlineSwitchAmount}}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="device-list-detail">
      <div class="tabs-content">
        <div class="table-wrapper">
          <div class="sub-title">设备列表</div>
          <div class="device-search-bar">
            <span>
              <el-input v-model="searchData.iotId" placeholder="请输入iotId" clearable style="width: 220px"></el-input>
            </span>
            <span>
              <el-input v-model="searchData.deviceName" placeholder="请输入DeviceName" clearable style="width: 220px"></el-input>
            </span>
            <div class="date-wrapper">
              <el-col :span="11">
                <el-date-picker type="date" placeholder="请选择起始日期" v-model="searchData.start" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-date-picker placeholder="请选择截止日期" v-model="searchData.end" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
            </div>
            <span>
              <el-button plain @click="getSwitchList(true)">搜索</el-button>
            </span>
          </div>
          <div>
            <el-table :data="switchList" style="width: 100%" v-loading="loadingSwitchList">
              <el-table-column label="IotId" prop="iotId" min-width="160" align="center">
                <template slot-scope="scope">
                  <el-popover
                    placement="top"
                    trigger="hover"
                    :content="scope.row.iotId">
                    <div class="long-text" slot="reference">{{scope.row.iotId}}</div>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="DeviceName" prop="deviceName" min-width="160" align="center">
                <template slot-scope="scope">
                  <el-popover
                    placement="top"
                    trigger="hover"
                    :content="scope.row.deviceName">
                    <div class="long-text" slot="reference">{{scope.row.deviceName}}</div>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="所属产品" min-width="200" align="center">
                <template slot-scope="scope">
                  <div v-for="product in productList" :key="product.productkey">
                    <span v-if="product.productkey === scope.row.productKey">{{product.name}}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态" min-width="100" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.status === 1 || scope.row.status === 2 ? '在线' : '离线'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="最后上线时间" prop="updatedAt" min-width="160" align="center"></el-table-column>
              <el-table-column label="操作" min-width="100" align="center">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="goSwitchInfo(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="padding: 20px 0; text-align: right;">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageConfig.pageIndex"
              :page-sizes="[10, 15, 20]"
              :page-size="pageConfig.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageConfig.totalCount"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import formUtil from "@/utils/formUtil";
export default {
  data() {
    return {
      statisticsData: {
        onlineSwitchAmount: 0,
      },
      searchData: {
        start: '',
        end: '',
        productKey: '',
        deviceName: '',
        iotId: ''
      },
      switchList: [],
      pageConfig: {
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0,
        totalPage: 0,
      },
      productList: [],
      loadingOnlineSwitchAmount: true,
      loadingSwitchList: true,
    };
  },
  components: {},
  activated() {
    if(window.NEEDREFRESH) {
      formUtil.resetData(this.searchData);
      this.getSearchTime();
      this.searchAllData()
      window.NEEDREFRESH = false;
    }
    if(this.productList.length === 0) this.productList = JSON.parse(window.sessionStorage.getItem('productList'))
  },
  mounted() {
    this.productList = JSON.parse(window.sessionStorage.getItem('productList'))
    this.getSearchTime();
    this.searchAllData();
  },
  methods: {
    //获取查询起始日期时间戳
    getSearchTime() {
      let date = new Date();
      let year = date.getFullYear();
      let mouth = date.getMonth() + 1;
      let day = date.getDate();
      let today = year + '-' + mouth + '-' + day;
      let lastYearToday = (year-1) + '-' + mouth + '-' + day;
      this.searchData.start = new Date(lastYearToday).getTime();
      this.searchData.end = new Date(today).getTime();
    },
    searchAllData() {
      this.getOnlineSwitchAmount();
      this.getSwitchList(true)
    },
    //获取在线设备总数
    async getOnlineSwitchAmount() {
      this.loadingOnlineSwitchAmount = true;
      let { data: res } = await this.$http.post("bms/switch/online", { productKey: this.searchData.productKey });
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.loadingOnlineSwitchAmount = false;
      this.statisticsData.onlineSwitchAmount = res.data;
    },
    async getSwitchList(init) {
      this.loadingSwitchList = true;
      if(init) this.pageConfig.pageIndex = 1;
      if (this.searchData.start > this.searchData.end) return this.$message.error("起始日期应小于或等于截止日期")
      let { data: res } = await this.$http.post("bms/switch/list?pageNum=" + this.pageConfig.pageIndex 
          + "&pageSize=" + this.pageConfig.pageSize 
          + "&start=" + this.searchData.start
          + "&end=" + (this.searchData.end + (24*60*60*1000-1))
          +'&timezoneOffset=28800', {
          orderBy: {
            col: "created_at",
            type: "desc",
          },
          productKey: this.searchData.productKey,
          deviceName: this.searchData.deviceName,
          iotId: this.searchData.iotId
        }
      );
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.switchList = res.data.list
      this.loadingSwitchList = false;
      if(init) {
        this.pageConfig.totalPage = res.data.pages;
        this.pageConfig.totalCount = Number(res.data.total);
      }
    },
    handleSizeChange(val) {
      this.pageConfig.pageSize = val;
      this.getSwitchList(true);
    },
    handleCurrentChange(val) {
      this.pageConfig.pageIndex = val;
      this.getSwitchList();
    },
    goSwitchInfo(row) {
      this.$router.push({path: '/bms-switchDetail', query: { iotId: row.iotId, gateway: row.productKey === "a25c34Wbg4I" ? true : false }});
    },
  },
};
</script>

<style lang='scss' scoped>
.component-container {
  min-width: 1000px;
  height: calc(100vh - 50px);
  color: #333333;
  .title {
    font-size: 20px;
    font-weight: 700;
    padding: 20px;
    margin: 0;
    display: flex;
    line-height: 36px;
  }
  .search-bar {
    display: flex;
    justify-content: space-between;
    padding: 0 20px 20px;
    height: 72px;
    .left {
      display: flex;
      .preview {
        display: flex;
        .preview-item {
          height: 48px;
          justify-content: center;
          border-left: 1px solid #ebecec;
          font-size: 20px;
          padding-left: 28px;
          width: 200px;
          header {
            font-size: 14px;
            color: #73777a;
            .status-green {
              display: inline-block;
              width: 8px;
              height: 8px;
              border-radius: 8px;
              background-color: #0fc18a;
            }
          }
          .number {
            margin-top: 5px;
          }
        }
      }
    }
  }
  .device-list-detail {
    /deep/ .el-tabs__item {
      padding: 0 20px;
      color: #999999;
    }
    /deep/ .el-tabs__item.is-active {
      color: #409eff;
    }
    /deep/ .el-tabs__active-bar {
      padding: 0 20px;
      left: -20px;
    }
    /deep/ .el-tabs__nav-wrap::after {
      background-color: #fff;
    }
    /deep/ .el-tabs__header {
      padding: 0 20px;
      margin: 0;
      background-color: #fff;
    }
    .tabs-content {
      padding: 20px;
      background-color: #f7f7f7;
      .table-wrapper {
        background-color: #fff;
        padding: 20px;
        .sub-title {
          font-size: 16px;
        }
        .device-search-bar {
          display: flex;
          margin: 20px 0 16px;
          > span {
            margin-right: 12px;
          }
          .date-wrapper {
            margin: 0 20px;
            width: 480px;
            text-align: center;
            line-height: 36px;
          }
        }
        .long-text {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>